package com.yuezhi.consumer.Listener;

import com.rabbitmq.client.Channel;
import com.yuezhi.consumer.constant.QueueConstant;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HelloWorldConsumer {

    /**
     * 通过 @RabbitListener 注解指定该方法监听的消息队列，该注解的参数就是消息队列的名字
     * @param message 消息
     */
    @RabbitListener(queues = QueueConstant.HELLO_QUEUE)
    public void receive(Message<String> message, Channel channel) throws IOException {
        System.out.println("消费消息：[" + message.getPayload() + "]");
        channel.basicAck(((Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG)),true);
    }

    @RabbitListener(queues = QueueConstant.HELLO_QUEUE, concurrency = "10")
    public void receive2(Message<String> message, Channel channel) throws IOException {
        System.out.println("并发消费消息：[" + message.getPayload() + "] == 线程名：[" + Thread.currentThread().getName() + "]");
        //第二个参数，true会重新放回队列，所以需要自己根据业务逻辑判断什么时候使用拒绝
        channel.basicReject(((Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG)), true);
    }
}
